<script setup>
import { computed, ref } from 'vue'
import { message } from 'ant-design-vue'
import http from '@/config/axios-config'
import fromLayout from '@/config/form-layout'
import SaveDialog from '@/components/plug-in/save-dialog'

const props = defineProps({
  visible: Boolean,
})
const emit = defineEmits(['update:visible', 'complete'])
let show = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})
let saveModal = ref()
let saveForm = ref({
  UserPassword: '',
  OriginalPassword: '',
})
let saveLoading = ref(false)
let saveItemLayout = ref(fromLayout)
let rules = ref({
  OriginalPassword: [{ required: true, message: '请输入原密码' }],
  UserPassword: [{ required: true, message: '请输入新密码' }],
  RePassword: [
    { required: true, message: '请输入确认密码' },
    {
      validator: (rule, value) => {
        if (value !== saveForm.value.UserPassword) {
          return Promise.reject('两次密码输入不一致')
        }
        return Promise.resolve()
      }
    }
  ]
})

const submitHandler = () => {
  saveModal.value.validateFields().then(() => {
    saveLoading.value = true
    let data = {
      UserPassword: saveForm.value.UserPassword,
      OriginalPassword: saveForm.value.OriginalPassword,
    }
    http.post('/users/reset-my-password', data).then(res => {
      saveLoading.value = false
      if (res.code === 200) {
        message.success(res.msg)
        emit('update:visible', false)
        saveForm.value = {}
        emit('complete')
      }
    })
  }).catch(() => {})
}
</script>

<template>
  <save-dialog
      v-model:visible="show"
      title="修改密码"
      :confirm-loading="saveLoading"
      width="500px"
      @ok="submitHandler">
    <div>
      <a-form ref="saveModal" :model="saveForm" v-bind="saveItemLayout" :rules="rules">
        <a-form-item name="OriginalPassword" label="原密码">
          <a-input-password v-model:value="saveForm.OriginalPassword" autocomplete="off"/>
        </a-form-item>
        <a-form-item name="UserPassword" label="新密码">
          <a-input-password v-model:value="saveForm.UserPassword" autocomplete="off"/>
        </a-form-item>
        <a-form-item name="RePassword" label="确认密码">
          <a-input-password v-model:value="saveForm.RePassword" autocomplete="off"/>
        </a-form-item>
      </a-form>
    </div>
  </save-dialog>
</template>
